# Test MP3 file upload with real MP3 format

$audioFile = "test_real_mp3.mp3"
$url = "http://localhost:8082/api/voiceprint/feature/add"
$groupId = "test_group_real_mp3"
$featureId = "test_real_mp3_" + (Get-Date -Format "yyyyMMdd_HHmmss")

Write-Host "Starting real MP3 file upload test..."
Write-Host "File: $audioFile"
Write-Host "URL: $url"
Write-Host "GroupId: $groupId"
Write-Host "FeatureId: $featureId"

# Check if file exists
if (-not (Test-Path $audioFile)) {
    Write-Host "Error: Audio file not found: $audioFile"
    exit 1
}

# Get file size
$fileSize = (Get-Item $audioFile).Length
Write-Host "File size: $fileSize bytes"

# Create multipart form data
$boundary = [System.Guid]::NewGuid().ToString()
$LF = "`r`n"

$bodyLines = @(
    "--$boundary",
    "Content-Disposition: form-data; name=`"groupId`"",
    "",
    $groupId,
    "--$boundary",
    "Content-Disposition: form-data; name=`"featureId`"",
    "",
    $featureId,
    "--$boundary",
    "Content-Disposition: form-data; name=`"audioFile`"; filename=`"$audioFile`"",
    "Content-Type: audio/mpeg",
    ""
)

$bodyText = $bodyLines -join $LF
$bodyBytes = [System.Text.Encoding]::UTF8.GetBytes($bodyText + $LF)

# Read audio file
$audioBytes = [System.IO.File]::ReadAllBytes($audioFile)

# Create closing boundary
$closingBoundary = [System.Text.Encoding]::UTF8.GetBytes($LF + "--$boundary--" + $LF)

# Combine all parts
$requestBody = New-Object System.Collections.Generic.List[byte]
$requestBody.AddRange($bodyBytes)
$requestBody.AddRange($audioBytes)
$requestBody.AddRange($closingBoundary)

Write-Host "Request body size: $($requestBody.Count) bytes"

try {
    Write-Host "Uploading real MP3 file..."
    
    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=$boundary")
    
    $response = $webClient.UploadData($url, "POST", $requestBody.ToArray())
    $responseText = [System.Text.Encoding]::UTF8.GetString($response)
    
    Write-Host "Upload successful!"
    Write-Host "Response: $responseText"
    
} catch {
    Write-Host "Upload failed: $($_.Exception.Message)"
    Write-Host "Detailed error: $($_.Exception.InnerException.Message)"
} finally {
    if ($webClient) {
        $webClient.Dispose()
    }
}

Write-Host "Test completed"